package routers

import (
	"gameserver/gcommon"
	"gameserver/messages"
	"gameserver/server"
	"gameserver/server/Login/internal"
	"gameserver/server/redisutil"
	"net/http"
	"time"

	"gitee.com/night-tc/gobige/common"
	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/logger"
	"github.com/gin-gonic/gin"
)

/*
账号级的处理请求
*/

func DebugLogin_Handler(c *gin.Context) {
	var err error
	defer func() {
		if err != nil {
			logger.Warnf("DebugLogin_Handler fail err:%v", err)
			if v, ok := err.(*common.Error); ok {
				c.JSON(http.StatusOK, gin.H{"Result": v.ErrCode})
			} else {
				c.JSON(http.StatusOK, gin.H{"Result": gcommon.RETMSG_Tips_Param_Fail})
			}
		}
	}()
	// 获取请求参数
	msg := &messages.LoginByOpenIDReq{}
	err = c.ShouldBindJSON(msg)
	if err != nil {
		return
	}

	// 处理请求
	var umd *messages.Account_MD
	umd, err = CreateUserByOpenID(msg.OpenID, msg.Channel)
	if err != nil {
		return
	}
	timestamp := time.Now().Add(global.Expire7Day).Unix()
	sig := internal.CreateJWTToken(umd.UserID, timestamp, msg.Channel, true)
	// 缓存账号信息
	lurd := redisutil.NewLoginUser(umd.UserID)
	_ = lurd.SaveInfo(map[string]any{
		redisutil.LoginUser_Key_UserID:    umd.UserID,
		redisutil.LoginUser_Key_OpenID:    umd.OpenID,
		redisutil.LoginUser_Key_ChannelID: umd.ChannelID,
		redisutil.LoginUser_Key_DeviceID:  "",
		redisutil.LoginUser_Key_IsAdult:   true,
		redisutil.LoginUser_Key_Age:       30,
	})

	c.JSON(http.StatusOK, gin.H{
		"Result": gcommon.RETMSG_success,
		"Data": gin.H{
			"UserID":    umd.UserID,
			"Sig":       sig,
			"Timestamp": timestamp,
			"IsAdult":   true,
		}})
	logger.Debugf(server.LogKey_LoginFlow, "DebugLogin_Handler success req:%v UserID:%d ", msg, umd.UserID)
}
